﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Windows;
using System.Diagnostics;
using System.Windows.Threading;
using System.ComponentModel;
using System.Reflection;
using FBNotifier.Properties;
using Microsoft.Win32;

namespace FBNotifier
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        public bool IsUserLogged { get; set; }
        public string AccessToken { get; set; }
        public enum AnimationTypes {SlidingWindow, FadingWindow};

        public int RefreshTime
        {
            get
            {
                return Convert.ToInt32(FBNotifier.Properties.Settings.Default.refreshTime);
            }
            set
            {
                FBNotifier.Properties.Settings.Default.refreshTime = value;
                FBNotifier.Properties.Settings.Default.Save();

                if (dt != null && dt.IsEnabled)
                {
                    dt.Interval = new TimeSpan(0, 0, value);
                }
            }
        }

        public bool AutoStartWithWindows
        {
            get
            {
                return Convert.ToBoolean(FBNotifier.Properties.Settings.Default.autoStart);
            }
            set
            {
                FBNotifier.Properties.Settings.Default.autoStart = value;
                FBNotifier.Properties.Settings.Default.Save();

                RegistryKey rkApp = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
                if (value)
                {
                    string pathToExe = Assembly.GetExecutingAssembly().Location;

                    rkApp.SetValue("FBNotifier", pathToExe);
                }
                else
                {
                    rkApp.DeleteValue("FBNotifier", false);
                }
            }
        }

        public bool PlaySounds 
        {
            get
            {
                return Convert.ToBoolean(FBNotifier.Properties.Settings.Default.playSounds);
            }
            set
            {
                FBNotifier.Properties.Settings.Default.playSounds = value;
                FBNotifier.Properties.Settings.Default.Save();
            }
        }

        public AnimationTypes AnimationType
        {
            get
            {
                if (FBNotifier.Properties.Settings.Default.animationType == 0)
                {
                    return AnimationTypes.SlidingWindow;
                }
                else
                {
                    return AnimationTypes.FadingWindow;
                }
            }
            set
            {
                byte animationTypeb;
                if (value == AnimationTypes.SlidingWindow)
                {
                    animationTypeb = 0;
                }
                else
                {
                    animationTypeb = 1;
                }

                FBNotifier.Properties.Settings.Default.animationType = animationTypeb;
                FBNotifier.Properties.Settings.Default.Save();
            }
        }

        private System.Windows.Forms.NotifyIcon ni;
        private DispatcherTimer dt;
        private bool isUpdateRunning = false;
        
        public string CurrentMessagesHtml = "";
        public string CurrentNotificationsHtml = "";
        public string CurrentProfileName = "";
        public int CurrentMessagesCount = 0;
        public int CurrentNotificationsCount = 0;
        
        private void Application_Startup(object sender, StartupEventArgs e)
        {
            IsUserLogged = false;

            //write the default values after installation
            AutoStartWithWindows = Settings.Default.autoStart;

            //StartupUri = new Uri("pack://application:,,,/MainAppWindow.xaml");
            //LoginWindow_UserLoggedIn(this, null);

            LoginWindow.UserLoggedIn += new EventHandler(LoginWindow_UserLoggedIn);
        }

        void LoginWindow_UserLoggedIn(object sender, EventArgs e)
        {
            IsUserLogged = true;
            AddTrayIcon();

            MainWindow = new MainAppWindow();

            ShutdownMode = System.Windows.ShutdownMode.OnExplicitShutdown;

            SetupTimeHandlers();
        }

        private void SetupTimeHandlers()
        {
            dt = new DispatcherTimer();
            dt.Interval = new TimeSpan(0, 0, RefreshTime);
            dt.Tick += new EventHandler(dt_tick);
            dt.Start();

            //call it immediately the first time
            dt_tick(null, null);
        }

        void dt_tick(object sender, EventArgs e)
        {
            if (!isUpdateRunning)
            {

                BackgroundWorker bw = new BackgroundWorker();

                bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
                bw.DoWork += new DoWorkEventHandler(bw_DoWork);
                bw.RunWorkerAsync();
            }
        }

        void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            isUpdateRunning = false;

            (MainWindow as MainAppWindow).RefreshBrowsersContent();
        }

        void bw_DoWork(object sender, DoWorkEventArgs e)
        {
            isUpdateRunning = true;

            if (CurrentProfileName == "")
            {
                FacebookAuxClass.ReadProfileName(out CurrentProfileName);
            }

            List<FacebookMessage> allMessages;
            List<FacebookMessage> newMessages;
            List<FacebookNotification> allNotifications;
            List<FacebookNotification> newNotifications;
            bool bSucessfullMessageUpdate = false;
            bool bSucessfullMNotificationUpdate = false;

            if (FacebookAuxClass.ReadMessages(out allMessages, out newMessages))
            {
                bSucessfullMessageUpdate = true;
                CurrentMessagesCount = allMessages.Count;
                FacebookAuxClass.GetHTMLForMessages(allMessages, out CurrentMessagesHtml);
            }

            if (FacebookAuxClass.ReadNotifies(out allNotifications, out newNotifications))
            {
                bSucessfullMNotificationUpdate = true;
                CurrentNotificationsCount = allNotifications.Count;
                FacebookAuxClass.GetHTMLForNotifies(allNotifications, out CurrentNotificationsHtml);
            }

            if (bSucessfullMessageUpdate && bSucessfullMNotificationUpdate)
            {
                NewEventsSystem.PushNewEvents(newMessages, newNotifications);

                ni.Text = String.Format("FBNotifier : {0}\nLast successfull update : {1}", CurrentProfileName, DateTime.Now.ToString("HH:mm:ss"));
            }

            SetProperIcon();
        }

        private void SetProperIcon()
        {
            if (ni != null)
            {
                string iconUri = string.Format("pack://application:,,,/Images/{0}", CurrentMessagesCount + CurrentNotificationsCount > 0 ? "Iconfull.ico" : "Iconempty.ico");
                System.IO.Stream iconStream = Application.GetResourceStream(new Uri(iconUri)).Stream;
                ni.Icon = new System.Drawing.Icon(iconStream);
            }
        }

        public void AddTrayIcon()
        {
            ni = new System.Windows.Forms.NotifyIcon();
            SetProperIcon();
            ni.Visible = true;

            ni.ContextMenu = new System.Windows.Forms.ContextMenu();
            ni.ContextMenu.MenuItems.Add("View Latest News", new EventHandler(ShowMainWindow));
            ni.ContextMenu.MenuItems.Add("Go to Facebook", new EventHandler(GoToFacebook));
            ni.ContextMenu.MenuItems.Add("Like FBNotifier", new EventHandler(LikeFBNotifier));
            ni.ContextMenu.MenuItems.Add("Options", new EventHandler(Options_Click));
            ni.ContextMenu.MenuItems.Add("About", new EventHandler(About_Click));
            ni.ContextMenu.MenuItems.Add("-");
            ni.ContextMenu.MenuItems.Add("E&xit", new  EventHandler(Exit_Click));

            ni.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler(ni_MouseDoubleClick);
            ni.MouseClick += new System.Windows.Forms.MouseEventHandler(ni_MouseClick);

            ni.Text = "FBNotifier";
        }

        void ni_MouseClick(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Left)
            {
                if (MainWindow != null && MainWindow.IsVisible)
                {
                    (MainWindow as MainAppWindow).Hide();
                }
                else
                {
                    (MainWindow as MainAppWindow).ShowAndActivate();
                }
            }
        }


        private void RemoveTrayIcon()
        {
            if (ni != null)
            {
                ni.Dispose();
            }
        }

        void ni_MouseDoubleClick(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Left)
            {
                GoToFacebook(sender, e);
            }
        }

        protected void ShowMainWindow(object sender, EventArgs e)
        {
            (MainWindow as MainAppWindow).ShowAndActivate();
        }

        protected void GoToFacebook(object sender, EventArgs e)
        {
            Process.Start("http://facebook.com");
        }

        protected void LikeFBNotifier(object sender, EventArgs e)
        {
            Process.Start("http://www.facebook.com/apps/application.php?id=112887725434899");
        }

        protected void Exit_Click(object sender, EventArgs e)
        {
            Shutdown();
        }

        protected void About_Click(object sender, EventArgs e)
        {
            AboutWindow wnd = new AboutWindow();
        }

        protected void Options_Click(object sender, EventArgs e)
        {
            if (!OptionsWindow.OptionWindowOpened)
            {
                OptionsWindow wnd = new OptionsWindow();
                wnd.ShowDialog();
            }
        }

        private void Application_Exit(object sender, ExitEventArgs e)
        {
            RemoveTrayIcon();
        }

        
    }
}
